-- UIArtifactRepair
-- Created by luohj
-- 神器维修界面

UIArtifactRepair = class("UIArtifactRepair", function()
    return cc.Layer:create();
end)

function UIArtifactRepair.create(classId)
    return UIArtifactRepair.new(classId);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIArtifactRepair:ctor(classId)
    -- 初始化
    self:setName("UIArtifactRepair");
    local node = cc.CSLoader:createNode("layout/artifactt/ArtifactRepair.csb");
    self:addChild(node);
    self.node = node;

    self.CT = findChildByName(self.node, "CT");
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 神器ID
    -- self.data = data;

    self.classId = classId;

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册修复事件
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 注册点击事件
function UIArtifactRepair:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIArtifactRepair");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

   -- 注册金币维修按钮点击事件
    local btnBuyOne = findChildByName(self.node, "CT/money_repair_btn");
    local function onBuyOneClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local ret = ArtifactM.canRecoverDurability(self.classId, 1);
            if ret == true then
                ArtifactM.recoverDurability(self.classId, 1, 2);
            elseif type(ret) == "table" then
                self:notEnoughTip(ret);

                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UIArtifactRepair");
            end
        end
    end
    btnBuyOne:addTouchEventListener(onBuyOneClick);

    -- 注册碎片维修事件
    local btnBuyChip = findChildByName(self.node, "CT/scrap_repair_btn");
    local function onBuyByChipClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local num = ArtifactM.getCanRecoverNum(self.classId);
            if num[1] > 0 then
                ArtifactM.recoverDurability(self.classId, 1, 1);
            end
        end
    end
    btnBuyChip:addTouchEventListener(onBuyByChipClick);
end

function UIArtifactRepair:notEnoughTip(data)
    if data[1] == 1 then
        -- 物品不足
        local name = ItemM.query(data[1], "name");
        local tip = string.format(getLocStr("not_enough"), name);
        alert(tip);
    elseif data[1] == 2 then
        -- 属性消耗
        local name = FieldsM.query(data[2], "name");
        local tip = string.format(getLocStr("not_enough"), name);
        alert(tip);
    end
end

function UIArtifactRepair:setEnabled(sender)
    sender:setTouchEnabled(false);
    sender:setBright(false);
end

-- 注册事件处理回调函数
function UIArtifactRepair:registerEventCallback()
    -- 关注修复成功的事件
    EventMgr.register("UIArtifactRepair", event.ARTIFACT_DURA_RECOVER, function(args)
        -- 重绘界面
        self:redraw();
        -- 播放动画
        local lightNode = findChildByName(self.node, "CT/info/bg");
        lightNode:removeAllChildren();
        playEffect(lightNode, 1180, 80, 85);

        -- 文字放大缩小
       -- local durabilityLabel = findChildByName(self.node, "CT/info/durability_label");
       -- commonTextEffect(durabilityLabel);
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIArtifactRepair", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIArtifactRepair" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 2);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIArtifactRepair 界面析构清理");
            --setJumpStop("durability_repair", false);
            local topMenu = UIMgr:getCurrentScene().topMenu;
            if topMenu then
                topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER);
            end
            EventMgr.removeAll("UIArtifactRepair");
         elseif ev == "enter" then

        end
    end);
end

-- 重绘
function UIArtifactRepair:redraw()
    -- 显示提示
    local price1   = ArtifactM.getCanRecoverNum(self.classId);
    local onePrice = ArtifactM.calcRecoverCostMoney(self.classId, 1);

    local durability = ArtifactM.getDurability(self.classId) or 0; -- 剩余耐久度
    local durabilityAll = ArtifactM.query(self.classId, "max_durability") or 0; -- 总耐久度

    -- 根据星级显示更改背景框
    local bgFrame = findChildByName(self.node, "CT/info/bg");
    -- local rank = ItemM.query(self.classId, "rank");
    local bgPath = getFrameBgIconPath("rank_large".. 1);
    bgFrame:loadTexture(bgPath);

    -- 神器等级
    local level = ArtifactM.getArtifactLevel(self.classId);
    local starNode = findChildByName(self.node, "CT/info/star");
    starNode:removeAllChildren();
    if level >= 0 then

        local durability = ArtifactM.getDurability(self.classId) or 0; -- 剩余耐久度
        local durabilityAll = ArtifactM.query(self.classId, "max_durability") or 0; -- 总耐久度
        local lightStarPath = "images/ui/symbol/point_01.png";
        local darkStarPath = "images/ui/symbol/point_02.png";
        local sinkerLayer = createStarLayerEx(durability, durabilityAll, lightStarPath, darkStarPath, "center", -0.3);
        starNode:addChild(sinkerLayer);
        starNode:setVisible(true);
    end

    -- 耐久显示
    local durabilityLabel = findChildByName(self.node, "CT/info/durability_label");
    TextStyleM.setTextStyle(durabilityLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true);
    durabilityLabel:setString(string.format(getLocStr("durable"),durability));
    durabilityLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);

    -- 神器名字
    local artifactName = ItemM.query(self.classId, "name");
    local nameLabel = findChildByName(self.node, "CT/info/name");
    nameLabel:setString(artifactName);
    TextStyleM.setTitleStyle(nameLabel);

    -- 神器图标
    local iconImg = findChildByName(self.node, "CT/info/item");
    local fileName = ItemM.query(self.classId, "icon");
    iconImg:loadTexture(getItemIconPath(fileName));

    -- 获取拥有的神器碎片
    local material = ArtifactM.getArtifactScrap(self.classId);
    if not material then
        error("获取不到合成材料");
    end
    local fragmentCount = ItemM.getAmount(ME.user, material[1]); -- 碎片数
    local scrapNumLabel = findChildByName(self.node, "CT/info/scrap_num");
    scrapNumLabel:setString(string.format(getLocStr("artifact_scrap_num"),fragmentCount));
    TextStyleM.setSubheadStyle(scrapNumLabel);

     -- 设置维修提示
     local tipLabel1 = findChildByName(self.node, "CT/tip1");
    tipLabel1:setString(getLocStr("artifact_repair"));
    TextStyleM.setTextStyle(tipLabel1, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
     -- 设置维修代价
     local tipLabel2 = findChildByName(self.node, "CT/tip2");
    local tipStr = getLocStr("artifact_repair_way");
     -- 碎片修复代价
    local price1 = ArtifactM.query(self.classId, "durability_price1");
    -- 金币修复1点花费
    local price2 = ArtifactM.query(self.classId, "durability_price2");

    local needPrice1 = price1[3] or 0;
    local needPrice2 = price2[3] or 0;

    -- 神器修复价格降低
    local prop = PropM.combine(ME.user, "repair_cost", 1);
    needPrice2 = PropM.apply(prop, needPrice2);

    local moneyCount = ME.user:queryAttrib("money");

    --
    local price2Str = "";
    if needPrice2 > moneyCount then
        price2Str = string.format("[red]%d[-]", needPrice2);
    else
        price2Str = string.format("[blue]%d[-]", needPrice2);
    end

    local price1Str = "";
    if needPrice1 > ItemM.getAmount(ME.user, price1[2]) then
        price1Str = string.format("[red]%d[-]", needPrice1);
    else
        price1Str = string.format("[blue]%d[-]", needPrice1);
    end

    local str1 = string.format(tipStr, price1Str, price2Str);
    TextStyleM.setTextStyle(tipLabel2, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    tipLabel2 = applyString(tipLabel2, str1);

     -- 设置维修按钮是否可用
     local duraCost = ArtifactM.calcRecoverDuraCost(self.classId, 1)
    local scrapRepair = findChildByName(self.node, "CT/scrap_repair_btn");
     if duraCost[1] ~= 1 or durability >= durabilityAll then
        self:setEnabled(scrapRepair);
     end
    TextStyleM.setTextStyle(scrapRepair, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    scrapRepair:setTitleText(getLocStr("repair_by_chip"));

     -- 金币修复按钮是否可用
    local moneyCost = ArtifactM.calcRecoverCostMoney(self.classId, 1);

    local moneyRepair = findChildByName(self.node, "CT/money_repair_btn");
    local needMoney = moneyCost[3] or 0;
    if needPrice2 > moneyCount or durability >= durabilityAll then
        self:setEnabled(moneyRepair);
    end
    TextStyleM.setTextStyle(moneyRepair, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    moneyRepair:setTitleText(getLocStr("repair_by_money"));

    -- 如果最大耐久， 显示已达最大耐久
    if durability >= durabilityAll then
        tipLabel1:setVisible(false);
        tipLabel2:setVisible(false);
        local maxLabel = findChildByName(self.node, "CT/max_label");
        maxLabel:setVisible(true);
        TextStyleM.setTextStyle(maxLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_GRAY);
        applyString(maxLabel, getLocStr("max_durability"));
    end
end

-- 适配
function resize(node)
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end